package com.juxing.controller.admin;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.juxing.exception.BaseException;
import com.juxing.pojo.ExpressOrder;
import com.juxing.pojo.User;
import com.juxing.povo.ExpressOrderVo;
import com.juxing.service.ExpressOrderService;
import com.juxing.utils.ResResult;
import com.juxing.utils.UserRedisUtil;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelWriter;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 管理快递订单
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/admin/expressOrder")
public class ExpressOrderAdminController {
	
	private final Logger log = LoggerFactory.getLogger(ExpressOrderAdminController.class);
	
	@Autowired
	private ExpressOrderService expressOrderService;
	@Autowired
	private UserRedisUtil userRedisUtil;

	/**
	 * 管理员取消快递订单
	 * 
	 * @param requset
	 * @param expressOrderId
	 * @param cancelMsg
	 * @return
	 */
	@RequestMapping("/orderCancel")
	public ResResult orderCancel(HttpServletRequest requset, Long expressOrderId, String cancelMsg) {
		User loginUser = userRedisUtil.getUser(requset.getHeader("token"));
		Integer insert = 0;
		try {
			insert = expressOrderService.orderCancel(expressOrderId, cancelMsg, loginUser, true);
		} catch (Exception e) {
			if (e instanceof BaseException) {
				return ResResult.build(((BaseException) e).getCode(), e.getMessage());
			}
		}
		return ResResult.ok(insert);
	}

	/**
	 * 管理员配送中
	 * 
	 * @param requset
	 * @param ExpressOrderId
	 * @return
	 */
	@RequestMapping("/orderDistribution")
	public ResResult orderDistribution(HttpServletRequest requset, Long expressOrderId) {
		User loginUser = userRedisUtil.getUser(requset.getHeader("token"));
		Integer result = 0;
		try {
			result = expressOrderService.orderDistribution(expressOrderId, loginUser);
		} catch (BaseException e) {
			e.printStackTrace();
			return ResResult.build(e.getCode(), e.getMessage());
		}
		return ResResult.ok(result);
	}

	/**
	 * 配送完成
	 * 
	 * @param requset
	 * @param expressOrderId
	 * @return
	 */
	@RequestMapping("/orderSuccess")
	public ResResult orderSuccess(HttpServletRequest requset, Long expressOrderId) {
		User loginUser = userRedisUtil.getUser(requset.getHeader("token"));
		Integer result = 0;
		try {
			result = expressOrderService.orderSuccess(expressOrderId, loginUser);
		} catch (BaseException e) {
			e.printStackTrace();
			return ResResult.build(e.getCode(), e.getMessage());
		}
		return ResResult.ok(result);
	}

	/**
	 * 管理员更新订单
	 * 
	 * @param requset
	 * @param expressOrderId
	 * @param expressOrder
	 * @return
	 */
	@RequestMapping("/updateOrder")
	public ResResult updateOrder(HttpServletRequest requset, Long expressOrderId, ExpressOrder expressOrder) {
		User loginUser = userRedisUtil.getUser(requset.getHeader("token"));
		Integer result = 0;
		try {
			result = expressOrderService.update(expressOrder, loginUser);
		} catch (BaseException e) {
			e.printStackTrace();
			return ResResult.build(e.getCode(), e.getMessage());
		}
		return ResResult.ok(result);
	}

	/**
	 * 根据条件查询所有快递订单
	 * 
	 * @param pageNum
	 * @param pageSize
	 * @param expressOrder
	 * @return
	 */
	@RequestMapping("/list")
	public ResResult list(@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "10") Integer pageSize, ExpressOrder expressOrder) {
		Example example = new Example(ExpressOrder.class);
		example.setOrderByClause("status asc");
		Criteria criteria = example.createCriteria();
		if (expressOrder.getOrderId() != null) {
			criteria.andEqualTo("orderId", expressOrder.getOrderId());
		}
		if (expressOrder.getExpressId() != null) {
			criteria.andEqualTo("expressId", expressOrder.getExpressId());
		}
		if (expressOrder.getUserId() != null) {
			criteria.andEqualTo("userId", expressOrder.getUserId());
		}
		if (expressOrder.getAdminId() != null) {
			criteria.andEqualTo("adminId", expressOrder.getAdminId());
		}
		if (!StringUtils.isEmpty(expressOrder.getPickUpCode())) {
			criteria.andLike("pickUpCode", "%" + expressOrder.getPickUpCode() + "%");
		}
		if (!StringUtils.isEmpty(expressOrder.getName())) {
			criteria.andLike("name", "%" + expressOrder.getName() + "%");
		}
		if (!StringUtils.isEmpty(expressOrder.getPhone())) {
			criteria.andLike("phone", "%" + expressOrder.getPhone() + "%");
		}
		if (!StringUtils.isEmpty(expressOrder.getDormNumber())) {
			criteria.andLike("dormNumber", "%" + expressOrder.getDormNumber() + "%");
		}
		if (expressOrder.getStatus() != null) {
			criteria.andEqualTo("status", expressOrder.getStatus());
		}

		return ResResult.ok(expressOrderService.list(pageNum, pageSize, example));
	}

	/**
	 * 下载表
	 */
	@RequestMapping("/downExcel")
	public void downExcel(@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "10") Integer pageSize, ExpressOrder expressOrder) {
		Example example = new Example(ExpressOrder.class);
		example.setOrderByClause("status asc");
		Criteria criteria = example.createCriteria();
		if (expressOrder.getOrderId() != null) {
			criteria.andEqualTo("orderId", expressOrder.getOrderId());
		}
		if (expressOrder.getExpressId() != null) {
			criteria.andEqualTo("expressId", expressOrder.getExpressId());
		}
		if (expressOrder.getUserId() != null) {
			criteria.andEqualTo("userId", expressOrder.getUserId());
		}
		if (expressOrder.getAdminId() != null) {
			criteria.andEqualTo("adminId", expressOrder.getAdminId());
		}
		if (!StringUtils.isEmpty(expressOrder.getPickUpCode())) {
			criteria.andLike("pickUpCode", "%" + expressOrder.getPickUpCode() + "%");
		}
		if (!StringUtils.isEmpty(expressOrder.getName())) {
			criteria.andLike("name", "%" + expressOrder.getName() + "%");
		}
		if (!StringUtils.isEmpty(expressOrder.getPhone())) {
			criteria.andLike("phone", "%" + expressOrder.getPhone() + "%");
		}
		if (!StringUtils.isEmpty(expressOrder.getDormNumber())) {
			criteria.andLike("dormNumber", "%" + expressOrder.getDormNumber() + "%");
		}
		if (expressOrder.getStatus() != null) {
			criteria.andEqualTo("status", expressOrder.getStatus());
		}
		PageInfo<ExpressOrderVo> page = expressOrderService.list(pageNum, pageSize, example);

		List<ExpressOrderVo> list = page.getList();

		List<Map<String, Object>> rows = CollUtil.newArrayList();
		for(ExpressOrderVo vo : list) {
			Map<String, Object> map = new LinkedHashMap<>();
			map.put("订单号", vo.getOrderId());
			map.put("快递公司", vo.getExpress().getName());
			map.put("取货码", vo.getPickUpCode());
			map.put("收件人", vo.getName());
			map.put("手机号", vo.getPhone());
			map.put("寝室号", vo.getDormNumber());
			map.put("备注", vo.getUserDesc());
			map.put("状态", vo.getStatusStr());
			map.put("创建时间", vo.getCreateDate().toString());
			rows.add(map);
		}
		// 通过构造方法创建writer
		ExcelWriter writer = new ExcelWriter("d:/writeTest.xlsx");
		// 跳过当前行，既第一行，非必须，在此演示用
		writer.passCurrentRow();
		// 合并单元格后的标题行，使用默认标题样式
		writer.merge(rows.size() - 1, pageNum+"---"+pageSize);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		log.info("文件生产成功");
	}
}
